const Router = require('koa-router')
const router = new Router({
  prefix: '/api'
})
const query = require('../../db/query')
const path = require('path')
const fs = require('fs')
const db = require('../../db')
const cache = require('../../middleware/cache')

// 获取轮播图列表
router.get('/banners', async (ctx) => {
  try {
    const sql = `
      SELECT id, image_url, title, subtitle, is_show 
      FROM banners 
      ORDER BY id DESC
    `
    const result = await query(sql)
    // 处理图片URL，添加时间戳
    const data = result.map(banner => ({
      ...banner,
      image_url: `${banner.image_url}?t=${Date.now()}`  // 添加时间戳
    }))
    
    ctx.body = {
      code: 0,
      data,
      msg: 'success'
    }
  } catch (error) {
    ctx.body = {
      code: 1,
      msg: error.message
    }
  }
})

// 添加轮播图
router.post('/banners', async (ctx) => {
  try {
    const { title, subtitle, image_url } = ctx.request.body;
    
    if (!title || !image_url) {
      return ctx.body = {
        code: 1,
        msg: '标题和图片不能为空'
      };
    }

    // 先插入记录获取ID
    const insertSql = `
      INSERT INTO banners (title, subtitle, is_show, image_url) 
      VALUES (?, ?, 1, ?)
    `;
    
    const result = await query(insertSql, [title, subtitle || null, image_url]);
    
    // 处理图片
    if (image_url && image_url.includes('temp_')) {
      // 移除时间戳查询参数
      const cleanImageUrl = image_url.split('?')[0];
      const newImageUrl = `/uploads/images/banners/banner${result.insertId}.jpg`;
      
      const oldPath = path.join(__dirname, '../../public', cleanImageUrl);
      const newPath = path.join(__dirname, '../../public', newImageUrl);
      
      // 确保目标目录存在
      const targetDir = path.dirname(newPath);
      if (!fs.existsSync(targetDir)) {
        fs.mkdirSync(targetDir, { recursive: true });
      }
      
      // 检查源文件是否存在
      if (!fs.existsSync(oldPath)) {
        throw new Error('源文件不存在');
      }
      
      // 重命名文件
      fs.renameSync(oldPath, newPath);
      
      // 更新数据库中的图片URL
      await query(
        'UPDATE banners SET image_url = ? WHERE id = ?',
        [newImageUrl, result.insertId]
      );
    }

    ctx.body = {
      code: 0,
      msg: 'success',
      data: { id: result.insertId }
    };
  } catch (error) {
    console.error('添加轮播图错误:', error);
    ctx.body = {
      code: 1,
      msg: error.message
    };
  }
});

// 更新轮播图
router.put('/banners/:id', async (ctx) => {
  try {
    const { id } = ctx.params;
    const { image_url, title, subtitle } = ctx.request.body;
    
    if (!title) {
      return ctx.body = {
        code: 1,
        msg: '标题不能为空'
      };
    }

    if (image_url && image_url.includes('temp_')) {
      // 获取原有的图片URL
      const queryResult = await query('SELECT image_url FROM banners WHERE id = ?', [id]);
      const oldImageUrl = queryResult[0]?.image_url;
      
      // 移除时间戳查询参数
      const cleanImageUrl = image_url.split('?')[0];
      const newImageUrl = `/uploads/images/banners/banner${id}.jpg`;
      
      // 删除原有图片
      if (oldImageUrl) {
        const oldPath = path.join(__dirname, '../../public', oldImageUrl);
        if (fs.existsSync(oldPath)) {
          fs.unlinkSync(oldPath);
        }
      }

      // 重命名新上传的临时文件
      const tempPath = path.join(__dirname, '../../public', cleanImageUrl);
      const newPath = path.join(__dirname, '../../public', newImageUrl);
      
      // 确保目标目录存在
      const targetDir = path.dirname(newPath);
      if (!fs.existsSync(targetDir)) {
        fs.mkdirSync(targetDir, { recursive: true });
      }

      // 检查源文件是否存在
      if (!fs.existsSync(tempPath)) {
        throw new Error('源文件不存在');
      }
      
      // 重命名文件
      fs.renameSync(tempPath, newPath);

      // 更新数据库
      const sql = `
        UPDATE banners 
        SET image_url = ?, title = ?, subtitle = ?
        WHERE id = ?
      `;
      await query(sql, [newImageUrl, title, subtitle || null, id]);
    } else {
      // 如果没有更新图片，只更新其他字段
      const sql = `
        UPDATE banners 
        SET title = ?, subtitle = ?
        WHERE id = ?
      `;
      await query(sql, [title, subtitle || null, id]);
    }
    
    ctx.body = {
      code: 0,
      msg: 'success'
    };
  } catch (error) {
    console.error('更新轮播图错误:', error);
    ctx.body = {
      code: 1,
      msg: error.message
    };
  }
});

// 删除轮播图
router.delete('/banners/:id', async (ctx) => {
  try {
    const { id } = ctx.params;
    
    // 先获取图片URL
    const queryResult = await query('SELECT image_url FROM banners WHERE id = ?', [id]);
    const imageUrl = queryResult[0]?.image_url;

    // 删除数据库记录
    const sql = 'DELETE FROM banners WHERE id = ?';
    await query(sql, [id]);

    // 删除图片文件
    if (imageUrl) {
      const imagePath = path.join(__dirname, '../../public', imageUrl);
      if (fs.existsSync(imagePath)) {
        fs.unlinkSync(imagePath);
      }
    }

    ctx.body = {
      code: 0,
      msg: 'success'
    };
  } catch (error) {
    ctx.body = {
      code: 1,
      msg: error.message
    };
  }
});

// 更新轮播图状态
router.put('/banners/:id/status', async (ctx) => {
  try {
    const { id } = ctx.params
    const { is_show } = ctx.request.body

    await query('UPDATE banners SET is_show = ? WHERE id = ?', [is_show, id])
    
    // 使相关缓存失效
    await cache.invalidateCache('api:cache:GET:/api/home*')
    await cache.invalidateCache('api:cache:GET:/api/banners*')
    
    console.log(`✅ Banner状态已更新: id=${id}, is_show=${is_show}`)
    ctx.body = { code: 200, message: '更新成功' }
  } catch (err) {
    console.error('更新banner状态失败:', err)
    ctx.status = 500
    ctx.body = { code: 500, message: '服务器内部错误' }
  }
})

// 文件上传处理
router.post('/upload', async (ctx) => {
  try {
    const file = ctx.request.files?.file;
    if (!file) {
      throw new Error('没有接收到上传文件');
    }

    // 确保上传目录存在
    const uploadDir = path.join(__dirname, '../../public/uploads/images/banners');
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }

    // 生成临时文件名
    const ext = path.extname(file.originalFilename || '');
    const fileName = `temp_${Date.now()}${ext}`;
    const targetPath = path.join(uploadDir, fileName);

    // 移动文件
    fs.renameSync(file.filepath, targetPath);

    // 返回带时间戳的URL
    const url = `/uploads/images/banners/${fileName}?t=${Date.now()}`;

    ctx.body = {
      code: 0,
      msg: 'success',
      url
    };
  } catch (error) {
    console.error('文件上传失败:', error);
    ctx.body = {
      code: 1,
      msg: error.message
    };
  }
});

// 获取轮播图列表
router.get('/api/banners', async (ctx) => {
  try {
    const banners = await query('SELECT * FROM banners ORDER BY sort DESC')
    ctx.body = {
      code: 200,
      data: banners
    }
  } catch (err) {
    console.error('获取轮播图列表失败:', err)
    ctx.status = 500
    ctx.body = {
      code: 500,
      message: '获取轮播图列表失败'
    }
  }
})

// 添加修改展示状态的接口
router.put('/api/banners/:id/status', async (ctx) => {
  const { id } = ctx.params
  const { is_show } = ctx.request.body
  
  try {
    await query('UPDATE banners SET is_show = ? WHERE id = ?', [is_show ? 1 : 0, id])
    
    ctx.body = {
      code: 200,
      message: '更新成功'
    }
  } catch (err) {
    console.error('更新轮播图状态失败:', err)
    ctx.status = 500
    ctx.body = {
      code: 500,
      message: '更新轮播图状态失败'
    }
  }
})

// 更新banner排序
router.put('/:id/sort', async (ctx) => {
  try {
    const { id } = ctx.params
    const { sort } = ctx.request.body

    await query('UPDATE banners SET sort = ? WHERE id = ?', [sort, id])
    
    // 使相关缓存失效
    await cache.invalidateCache('api:cache:GET:/api/home*')
    await cache.invalidateCache('api:cache:GET:/api/banners*')
    
    console.log(`✅ Banner排序已更新: id=${id}, sort=${sort}`)
    ctx.body = { code: 200, message: '更新成功' }
  } catch (err) {
    console.error('更新banner排序失败:', err)
    ctx.status = 500
    ctx.body = { code: 500, message: '服务器内部错误' }
  }
})

module.exports = router